package org.springside.examples.miniweb.service.dictionary;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.springside.examples.miniweb.entity.dictionary.DictionaryClass;
import org.springside.examples.miniweb.entity.dictionary.DictionaryDetail;
import org.springside.examples.miniweb.util.Constant;
import org.springside.examples.miniweb.dao.dictionary.DictionaryClassDao;
import org.springside.examples.miniweb.dao.dictionary.DictionaryDetailDao;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;

@Service
@Transactional
public class DictionaryDetailManager {
	@Autowired
	private DictionaryDetailDao dictionaryDetailDao;
	@Autowired
	private DictionaryClassDao dictionaryClassDao;

	// DictionaryDetail Manager //
	@Transactional(readOnly = true)
	public DictionaryDetail getDictionaryDetail(Long id) {
		return dictionaryDetailDao.get(id);
	}

	@Transactional(readOnly = true)
	public List<DictionaryDetail> getAllDictionaryDetail() {
		return dictionaryDetailDao.getAll();
	}
	
	@Transactional(readOnly = true)
	public Page<DictionaryDetail> searchDictionaryDetail(final Page<DictionaryDetail> page, final List<PropertyFilter> filters) {
		return dictionaryDetailDao.findPage(page, filters);
	}	
	
	public void saveDictionaryDetail(DictionaryDetail dictionaryDetail) {
		dictionaryDetailDao.save(dictionaryDetail);
	}

	public void deleteDictionaryDetail(Long id) {
		dictionaryDetailDao.delete(id);
	}
	
	public void updateAll(Long pid,String[] datas){
		DictionaryClass dictionaryClass = dictionaryClassDao.get(pid);
		int orderNo = 1;
		for(String data : datas){
			String[] temp = data.split("@");
			Long id = Long.parseLong(temp[0]);
			int operator = Integer.parseInt(temp[1]);
			String value = temp[2];
			if(operator == Constant.DictionaryState.DEL){//del
				deleteDictionaryDetail(id);
			}
			if(operator == Constant.DictionaryState.CREATE){//new 
				DictionaryDetail dictionaryDetail = new DictionaryDetail();
				dictionaryDetail.setValue(value);
				dictionaryDetail.setSort(orderNo);
				dictionaryDetail.setDictionaryClass(dictionaryClass);
				saveDictionaryDetail(dictionaryDetail);
				orderNo++;
			}
			if(operator == Constant.DictionaryState.NORMAL || operator == Constant.DictionaryState.UPDATE){//update
				DictionaryDetail dictionaryDetail = getDictionaryDetail(id);
				dictionaryDetail.setValue(value);
				dictionaryDetail.setSort(orderNo);
				dictionaryDetail.setDictionaryClass(dictionaryClass);
				saveDictionaryDetail(dictionaryDetail);
				orderNo++;
			}
		}
	}
}

